package com.xxl.job.admin.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xxl.job.admin.controller.annotation.PermessionLimit;
import com.xxl.job.admin.core.model.XinApi;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.route.ExecutorRouteStrategyEnum;
import com.xxl.job.admin.service.IXxlJobService;
import com.xxl.job.admin.service.XinApiService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.admin.service.XinAuthService;

/**
 * @create at: 2017-06-01
 * @author zhouzhe
 *
 */
@Controller
@RequestMapping("/xinapi")
public class XinApiController {

	@Resource
	private IXxlJobService xxlJobService;
	@Resource
	private XinAuthService xinAuthService;
	@Resource
	private XinApiService xinApiService;
	
	@RequestMapping(value = "/addcron")
	@ResponseBody
	@PermessionLimit(limit = false)
	public ReturnT<String> addJob(XxlJobInfo jobInfo, HttpServletRequest request) {	
		if(xinAuthService.validateUrlAuth(request)) {
			return xxlJobService.add(jobInfo);
		} else {
			Map map = XinAuthService.logMap;
			JSONObject json = new JSONObject(map);
			return new ReturnT<String>(ReturnT.FAIL_CODE, "验证不通过:"+json.toString());
		}
	}	
	
	@RequestMapping("/editjob")
	@ResponseBody
	@PermessionLimit(limit = false)
	public ReturnT<String> editJob(XxlJobInfo jobInfo, HttpServletRequest request) {
		if(xinAuthService.validateUrlAuth(request))
		{
			return xxlJobService.reschedule(jobInfo);
		} else {
			return new ReturnT<String>(ReturnT.FAIL_CODE, "验证不通过");
		}
	}
	
	@RequestMapping("/pause")
	@ResponseBody
	@PermessionLimit(limit = false)
	public ReturnT<String>Pause(@RequestParam int id, HttpServletRequest request) {
		if(xinAuthService.validateUrlAuth(request))
		{
			return xxlJobService.pause(id);
		} else {
			return new ReturnT<String>(ReturnT.FAIL_CODE, "验证不通过");
		}
	}
	
	@RequestMapping("/addapi")
	@ResponseBody
	@PermessionLimit(limit = false)
	public ReturnT<String>AddApi(XinApi xinapi, HttpServletRequest request)
	{
		if(!xinAuthService.validateUrlAuth(request))
		{
			Map map = XinAuthService.logMap;
			JSONObject json = new JSONObject(map);
			return new ReturnT<String>(ReturnT.FAIL_CODE, "auth验证失败:" + json.toString());
		}
		if(xinApiService.addApi(xinapi))
		{
			//添加api
			return new ReturnT<String>(ReturnT.SUCCESS_CODE, null);
		} else {			
			return new ReturnT<String>(ReturnT.FAIL_CODE, "添加api失败，" + xinApiService.getError());
		}
	}
	
	
}
